package com.ccn.crm.interfaces.impl;

import com.ccn.crm.mapper.ProjectMapper;
import com.ccn.crm.mapper.ProjectProductMapper;
import com.ccn.crm.mapper.SuperProductMapper;
import com.ccn.crm.model.*;
import com.ccn.crm.service.*;
import com.ccn.crm.util.*;
import com.mysql.cj.util.StringUtils;
import com.sun.org.apache.bcel.internal.generic.IF_ACMPEQ;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.xml.bind.SchemaOutputResolver;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
@Transactional(rollbackFor = Exception.class)
public class PushDataImpl implements IPushData  {
    private static final Logger LOG = LoggerFactory.getLogger(PushDataImpl.class);
    @Autowired
    private IInstall iInstall;
    @Autowired
    private IInstallDetail iInstallDetail;
    @Autowired
    private IProduct iProduct;
    @Autowired
    private IUser iUser;
    @Autowired
    private IEffort iEffort;
    @Autowired
    private IUserView iUserView;
    @Autowired
    private IUserGroup iUserGroup;
    @Autowired
    private EmailUtil emailUtil;
    @Autowired
    private IMail iMail;
    @Autowired
    private IInstallChange iInstallChange;
    @Autowired
    private IUnclaimedProject iUnclaimedProject;
    @Autowired
    private ProjectMapper projectMapper;
    @Autowired
    private ProjectProductMapper projectProductMapper;

    @Autowired
    private SuperProductMapper superProductMapper;
    @Autowired
    private IAction iAction;
    @Override
    public void getData() throws ParseException {

        //获取crm系统token值
        Map<String, Object> token = GetToken.getToken();
        Map<String, Object> projectInfo = GetProjectInfo.getProjectInfo(token);
//        System.out.println(projectInfo);
        String errorMessage = (String)projectInfo.get("errorMessage");
        //System.out.println(errorMessage);
        if ("OK".equals(errorMessage)) {
            Map<String, Object> data = (Map<String, Object>)projectInfo.get("data");

            List<Map<String, Object>> dataList =( List<Map<String, Object>>) data.get("dataList");

//            LOG.info("获取向禅道新增的项目列表"+dataList);
            if (dataList!=null && dataList.size()!=0){
//            System.out.println(dataList.size());
            for ( Map<String, Object> project :dataList) {
                System.out.println(project);

                String name = (String) project.get("name");

                //通过唯一编号查询
                String crmPid=(String)project.get("_id");

                Product products = iProduct.selectByCrmPid(crmPid);
                System.out.println(products==null);
                if (products==null) {
                    //新增禅道数据  crm传入
                    Product product = new Product();
                    //唯一编号
                    if (crmPid==null){
                        LOG.info("crmPid为空："+name);
                        continue;
                    }
                    if (project.get("record_type").equals("record_k1n25__c")){
                        continue;
                    }
                    product.setCrmPid(crmPid);

                    if (null != project.get("field_kknyk__c")) {
                        product.setCode(project.get("field_kknyk__c").toString());
                    } else {
                        product.setCode("");
                    }

                    if (null != project.get("field_f517f__c")) {
                        String projectoutType = project.get("field_f517f__c").toString();
                        if (projectoutType.equals("5x1mgB8ra")){
                            product.setProjectoutType("1");
                        }else if (projectoutType.equals("ckut3yZfM")){
                                product.setProjectoutType("2");
                        }else if (projectoutType.equals("brhn1AoiQ")){
                            product.setProjectoutType("3");
                        }else if (projectoutType.equals("Y4B19C3p1")){
                            product.setProjectoutType("4");
                        }else {
                            product.setCode("");
                        }
                    } else {
                        product.setCode("");
                    }

                    product.setName(name);
                    String corpAccessToken = (String) token.get("corpAccessToken");
                    User manageName=null;
                    if (null==project.get("field_pwX59__c")){
                        product.setPo("");
                        product.setCreatedby("");
                    }else {
                        List<Object> ownerKey = (List<Object>) project.get("field_pwX59__c");
                        //获取项目经理人
                        Map<String, Object> owner = GetUserInfo.GetUserInfo(ownerKey, corpAccessToken);
                        if (owner.isEmpty()) {
                            LOG.info("获取项目经理人失败:" + name);
                            Map<String, Object> datas = new HashMap<>();
                            Map<Object, Object> objectDatas = new HashMap<>();
                            objectDatas.put("dataObjectApiName", "object_h249C__c");
                            objectDatas.put("_id", crmPid);
                            objectDatas.put("field_E1N1d__c", "同步失败，获取项目经理失败");
                            datas.put("object_data", objectDatas);
                            emailUtil.sendMail("新建项目接口--新建项目失败，获取项目经理失败");
                            Map<String, Object> stringObjectMap1 = PushData.PushData(datas, token);
                            String errorMessages = (String) stringObjectMap1.get("errorMessage");
                            if (errorMessages.equals("OK")) {
                                LOG.info("返回错误回执成功:" + product.getName());
                            } else {
                                LOG.info("返回错误回执失败:" + errorMessages);
                            }
                            continue;
                        }
                       String  ownerName = (String) owner.get("name");
//                    if (null==ownerName||ownerName.equals("")){
//                        emailUtil.sendMail("新建项目报错---项目经理名获取失败为空"+ownerName );
//                        continue;
//                    }
                        //通过名字查询用户账户
                         manageName = iUser.selectByName(ownerName);
//                    if (null==manageName){
//                        emailUtil.sendMail("新建项目报错---查询项目经理账户失败为空"+ownerName );
//                    }
                        product.setPo(manageName.getAccount()==null?"":manageName.getAccount());
                        //由谁创建createdBy
                        product.setCreatedby(manageName.getNickname());
                    }

                    
                    //低利率
                    if ("option1".equals(project.get("field_uWq15__c").toString())) {
                        product.setLowprofitauditstatus("1");
                        //ProfitControlLine 指定利润率控制线 空白
                        if (null != project.get("field_Fkrd7__c")) {
                            String line = project.get("field_Fkrd7__c").toString()+"%";
                            product.setProfitcontrolline(line);
                        } else {
                            product.setProfitcontrolline("");
                        }
                    } else if ("zwSS34hu9".equals(project.get("field_uWq15__c").toString())) {
                        product.setLowprofitauditstatus("2");
                        product.setProfitcontrolline("");
                    } else if ("o1Nc5o3Xb".equals(project.get("field_uWq15__c").toString())) {
                        product.setLowprofitauditstatus("3");
                        product.setProfitcontrolline("");
                    } else if ("SqzxbPCaq".equals(project.get("field_uWq15__c").toString())) {
                        product.setLowprofitauditstatus("4");
                        product.setProfitcontrolline("");
                    } else {
                        product.setLowprofitauditstatus("5");
                        product.setProfitcontrolline("");
                    }
                    // System.out.println(project.get("field_g8WuI__c").toString());
                    //客户名称
                    Map<String, Object> stringObjectMap = GetCustomerInfo.GetCustomerInfo(project.get("field_g8WuI__c").toString(), token);

                    if (stringObjectMap.isEmpty()){
                        LOG.info("同步失败，客户名称获取失败:"+name);
                        Map<String, Object> datas = new HashMap<>();
                        Map<Object, Object> objectDatas = new HashMap<>();
                        objectDatas.put("dataObjectApiName", "object_h249C__c");
                        objectDatas.put("_id",crmPid);
                        objectDatas.put("field_E1N1d__c","同步失败，客户名称获取失败");
                        emailUtil.sendMail("新建项目接口--新建项目失败，客户名称获取失败");
                        datas.put("object_data", objectDatas);
                        Map<String, Object> stringObjectMap1 = PushData.PushData(datas, token);
                        String errorMessages = (String) stringObjectMap1.get("errorMessage");
                        if (errorMessages.equals("OK")){
                            LOG.info("返回错误回执成功:"+product.getName());
                        }else {
                            LOG.info("返回错误回执失败:"+errorMessages);
                        }
                        continue;
                    }
                    Map<String, Object> customerInfo = ( Map<String, Object>) stringObjectMap.get("data");
                    String customer = (String) customerInfo.get("name");
                    //项目里的业务人员
                    List<Object> lastModifiedByKey = (List<Object>)customerInfo.get("owner");
//                    //获取业务人员姓名
                    Map<String, Object> user = GetUserInfo.GetUserInfo(lastModifiedByKey, corpAccessToken);
                    String userName = (String) user.get("name");
                    product.setSalesman(userName);
                    product.setCustomername(customer);
                    product.setPlevel("");
                    //获取传入禅道备注
                    if (null != project.get("field_ScS2r__c")) {
                        product.setRemark(project.get("field_ScS2r__c").toString());
                    } else {
                        product.setRemark("");
                    }
                    product.setReturnRemark("");

                    //必须添加字段 ProjectReleaseDatePlan 项目上线时间

                    //生成初始值
                    BigDecimal defaultValue = new BigDecimal(0.0);
                    //软件变更金额
                    if (null != project.get("field_IbuIZ__c")) {
                        BigDecimal softwareChange = BigDecimalUtil.getBigDecimal(project.get("field_IbuIZ__c").toString());
                        product.setSoftwareChangeAmount(softwareChange);
                    } else {
                        product.setSoftwareChangeAmount(defaultValue);
                    }

                    if (null != project.get("field_5Ytqs__c")) {
                        BigDecimal IntegrateChange = BigDecimalUtil.getBigDecimal(project.get("field_5Ytqs__c").toString());
                        //实施变更金额IntegrateChangeAmount
                        product.setIntegrateChangeAmount(IntegrateChange);
                    } else {
                        product.setIntegrateChangeAmount(defaultValue);
                    }


                    /*
                    WarningInfo	项目预警信息
                    WarningLevel	项目预警级别
                    ProgressNote	进度说明
                     */
                    product.setWarninginfo("");
                    product.setWarninglevel("");
                    product.setProgressnote("");
                    //ProjectProgressPercentage	进度百分比	varchar
                    product.setProjectprogresspercentage("0%");
                    //获取是否提前立项
                    String isAdvance="";
                    if (null!=project.get("field_15Rv8__c")) {
                         isAdvance = project.get("field_15Rv8__c").toString();

                        if (isAdvance.equals("option1")) {
                            product.setIsOrNotStart("2");
                        } else if (isAdvance.equals("S1B1uuJ1p")) {
                            product.setIsOrNotStart("1");
                        }
                    }
                    //获取销售订单的数量
                    String nums = project.get("field_4DdEm__c").toString();

                    Integer orderNum = Integer.valueOf(nums);

                    //如果不是提前立项并且没有销售订单就是这位待分配
                    if (isAdvance.equals("option1")&&orderNum==0){
                        product.setProjectstatus("8");
                        product.setStatus("closed");
                    }else {
                        product.setProjectstatus("7");
                        product.setStatus("normal");
                    }
                    //ProjectStatus	项目阶段状态

                    //IntegrateAmountPlan 项目实施金额预计
                    product.setIntegrateamountplan(defaultValue);
                    //ExpectedChange  可预见需求变更
                    product.setExpectedchange("2");
                    //ExpectedChangeNote  可预见需求变更说明
                    product.setExpectedchangenote("");

                    //实施进场次数	varchar	空白
                    product.setEnterfactorycount("");
                    //SettlementType	实施结算方式	varchar	空白
                    product.setSettlementtype("");
                    //IntegrateUser	实施人员	varchar	空白
                    product.setIntegrateuser("");
                    /*
                    IntegrateAmount	项目实施金额(实际)	decimal	0
                    SoftwareAmountOutsource	软件外包金额	decimal	0
                    PlanImplementationDays	计划实施天数(初始)	float	0
                    HardwareAmount	项目硬件金额	decimal	0
                    ServiceAmount	项目服务金额（不含税）	decimal	0
                    SoftwareAmount	项目软件金额(不含税)	decimal	0
                    SZCost	售中预估工时(人天)	float	0
                    SQCost	售前预估工时(人天)总的	float	0
                    Salesman	业务人员	varchar	crm field_IwHgK_c
                    ProjectPrice	项目销售总金额(不含税)	decimal	0
                    IntegrateAmountPlan
                    project.get("field_Q2Rws__c").toString()
                     */
                    if (null != project.get("field_u5meY__c")) {
                        BigDecimal t = BigDecimalUtil.getBigDecimal(project.get("field_u5meY__c").toString());
                        product.setIntegrateamount(t);
                    } else {
                        product.setIntegrateamount(defaultValue);
                    }
                    product.setSoftwareamountoutsource(defaultValue);
                    product.setPlanimplementationdays(0F);

                    if (null != project.get("field_49PzK__c")) {
                        BigDecimal hardwareamount = BigDecimalUtil.getBigDecimal(project.get("field_49PzK__c").toString());
                        product.setHardwareamount(hardwareamount);
                    } else {
                        product.setHardwareamount(defaultValue);
                    }

                    if (null != project.get("field_MC5eu__c")) {
                        BigDecimal serviceAmount = BigDecimalUtil.getBigDecimal(project.get("field_MC5eu__c").toString());
                        product.setServiceamount(serviceAmount);
                    } else {
                        product.setServiceamount(defaultValue);
                    }

                    if (null != project.get("field_6K840__c")) {
                        BigDecimal software = BigDecimalUtil.getBigDecimal(project.get("field_6K840__c").toString());
                        product.setSoftwareamount(software);
                    } else {
                        product.setSoftwareamount(defaultValue);
                    }
                    product.setSzcost(0F);

                    //售前预估总工时
                    if (null != project.get("field_ysq56__c")) {
                        Float sqcost = Float.valueOf(project.get("field_ysq56__c").toString());
                        product.setSqcost(sqcost);
                        if (0<=sqcost&&sqcost<=10){
                            product.setProjectScale("1");
                        }else if (11<=sqcost&&sqcost<=50){
                            product.setProjectScale("2");
                        }else if (51<=sqcost&&sqcost<=150){
                            product.setProjectScale("3");
                        }else if (151<=sqcost){
                            product.setProjectScale("4");
                        }
                    } else {
                        product.setSqcost(0F);
                    }

                    //售前预估(追溯)，售前预估(营销)。
                    if (null != project.get("field_A4a22__c")) {
                        Float sqyxcost = Float.valueOf(project.get("field_A4a22__c").toString());
                        product.setSQYXCost(sqyxcost);
                    } else {
                        product.setSQYXCost(0F);
                    }

                    if (null != project.get("field_m5OrN__c")) {
                        Float sqzscost = Float.valueOf(project.get("field_m5OrN__c").toString());
                        product.setSQZSCost(sqzscost);
                    } else {
                        product.setSQZSCost(0F);
                    }
                    //售前预估集成    售前预估差旅费
                    if (null != project.get("field_22312__c")) {
                        Float sqjccost = Float.valueOf(project.get("field_22312__c").toString());
                        product.setSQJCCost(sqjccost);
                    } else {
                        product.setSQJCCost(0F);
                    }

                    if (null != project.get("field_ssDd1__c")) {
                        Float sqinstallcost = Float.valueOf(project.get("field_ssDd1__c").toString());
                        product.setSQInstallAmount(sqinstallcost);
                    } else {
                        product.setSQInstallAmount(0F);
                    }
                    //field_L47Ul__c  项目总金额
                    if (null != project.get("field_L47Ul__c")) {
                        BigDecimal price = BigDecimalUtil.getBigDecimal(project.get("field_L47Ul__c").toString());
                        product.setProjectprice(price);
                    } else {
                        product.setProjectprice(defaultValue);
                    }
                    product.setSoftwareChangeCost(defaultValue);
                    //demandChange  需求变更人天 field_3y5sU__c
                    if (null != project.get("field_3y5sU__c")) {
                        Float demandChange = Float.valueOf(project.get("field_3y5sU__c").toString());
                        product.setDemandChange(demandChange);
                    } else {
                        product.setDemandChange(0F);
                    }

                    /*
                    line	项目线	int	0
                    type	项目类型	varchar	normal
                    status	状态	varchar	normal
                    subStatus	子状态	varchar	空白
                    desc	项目描述	text	空白
                    PO	项目负责人	varchar	crm
                    QD	测试负责人	varchar	空白
                    RD	发布负责人	varchar	空白
                    feedback	反馈	varchar	空白
                     */
                    product.setLine(0);
                    product.setType("normal");
                    product.setSubstatus("");
                    product.setDesc("");
                    product.setQd("");
                    product.setRd("");
                    product.setFeedback("");

                    /*
                    acl	访问控制	enum('open','private','custom')	custom
                    whitelist	分组白名单	text	1,4,5,8,9
                    createdBy	由谁创建	varchar	crm
                    createdDate	创建日期	datetime	系统时间
                    createdVersion	createdVersion	varchar	biz3.7
                    order	排序	int	空白
                    deleted	已删除	enum('0','1')	0
                    项目完成时间
                     */
                    product.setAcl("custom");
                    product.setWhitelist("1,9");
                    Date date = new Date();

                    product.setCreateddate(date);
                    product.setCreatedversion("biz3.7");
                    int order = iProduct.selectOrder();
                    int num = order * 5;
                    product.setOrder(num);
                    product.setDeleted("1");

                    /*
                    projectupdatesqBy	由谁项目信息更新(售前)	varchar	空白
                    projectprogressupdateBy	由谁每周进度	varchar	空白
                    integrationprogressBy	由谁实施进度	varchar	空白
                     */
                    product.setProjectupdatesqby("");
                    product.setProjectprogressupdateby("");
                    product.setIntegrationprogressby("");
                    
                    //业务类别 禅道回传crm
                    if (null != project.get("field_Sprc2__c")) {
                        if (project.get("field_Sprc2__c").equals("s7I0K2utk")){
                            product.setBusinessType("1");
                        }else if (project.get("field_Sprc2__c").equals("2iy2bLhYc")){
                            product.setBusinessType("2");
                        }else if (project.get("field_Sprc2__c").equals("tn82Cvd5W")){
                            product.setBusinessType("3");
                        }else if (project.get("field_Sprc2__c").equals("hvl5LqPc5")){
                            product.setBusinessType("4");
                        }else if (project.get("field_Sprc2__c").equals("pXsSJ3RpN")){
                            product.setBusinessType("5");
                        }else if (project.get("field_Sprc2__c").equals("YK93Fhwi0")){
                            product.setBusinessType("6");
                        }else if (project.get("field_Sprc2__c").equals("1134nJ2lN")){
                            product.setBusinessType("7");
                        }
                    } else {
                        product.setBusinessType("");
                    }
                    // 新增是否自建 字段
                    if(null!=project.get("field_b2dm4__c")){
                        String build = project.get("field_b2dm4__c").toString();
                        if (build.equals("option1")){
                            product.setSelfBuilt("1");
                        }else {
                            product.setSelfBuilt("2");
                        }
                    }else {
                        product.setSelfBuilt("2");
                    }
                    int i = iProduct.insertData(product);
                    if (i>0) {
                        LOG.info("禅道新建项目成功，向crm返回添加成功状态:"+name);
                        Map<String, Object> datas = new HashMap<>();
                        Map<Object, Object> objectDatas = new HashMap<>();
                        objectDatas.put("dataObjectApiName", "object_h249C__c");
                        objectDatas.put("_id",crmPid);
                        objectDatas.put("field_E1N1d__c","同步成功");
                        datas.put("object_data", objectDatas);
                        Map<String, Object> stringObjectMap1 = PushData.PushData(datas, token);
                        String errorMessages = (String) stringObjectMap1.get("errorMessage");
                        if (errorMessages.equals("OK")){
                            LOG.info("回执成功:"+product.getName());
                        }else {
                            LOG.info("回执失败:"+errorMessages);
                        }
                    }else {
                        LOG.info("禅道新建项目失败，向crm返回添加状态:"+name);
                        Map<String, Object> datas = new HashMap<>();
                        Map<Object, Object> objectDatas = new HashMap<>();
                        objectDatas.put("dataObjectApiName", "object_h249C__c");
                        objectDatas.put("_id",crmPid);
                        objectDatas.put("field_E1N1d__c","同步失败");
                        datas.put("object_data", objectDatas);
                        Map<String, Object> stringObjectMap1 = PushData.PushData(datas, token);
                        String errorMessages = (String) stringObjectMap1.get("errorMessage");
                        if (errorMessages.equals("OK")){
                            LOG.info("返回错误回执成功:"+product.getName());
                        }else {
                            LOG.info("返回错误回执失败:"+errorMessages);
                        }
                    }

                    if (i>0){
                        LOG.info("项目新增成功,开始给项目经理增加项目视图");
                       this.addUserView(crmPid,manageName);

                        }else {
                            LOG.info("项目经理增加项目视图失败，没有查询到用户项目经理");
                        }
                    }
                 }
                }
            }
    }



    @Override
    public void pushData() throws Exception {
        LOG.info("开始想crm推送数据");
        Map<String, Object> token = GetToken.getToken();
        List<Product> products = iProduct.selectPush();
        if (products!=null && products.size()!=0) {
            for (Product product : products) {

                int id = product.getId();
                String productId = "," + id + ",";

                    LOG.info("获取到最新修改工时的项目:"+product.getName());
                    Map<String, Object> data = new HashMap<>();
                    Map<Object, Object> objectData = new HashMap<>();
                    objectData.put("dataObjectApiName", "object_h249C__c");
                    String crmPid = product.getCrmPid();
                    String code = product.getCode();
//                    String plevel = product.getPlevel();

                String projectScale = product.getProjectScale();
                Date createTime = product.getCreateddate();
                    if(null==projectScale||projectScale.equals("")){

                    }else {
                        if ("1".equals(projectScale)) {
                            projectScale = "b9m4w3ITu";
                        } else if ("2".equals(projectScale)) {
                            projectScale = "2xsb35B4N";
                        } else if ("3".equals(projectScale)) {
                            projectScale = "CZ53rhC38";
                        } else if ("4".equals(projectScale)) {
                            projectScale = "option1";
                        } else if ("5".equals(projectScale)) {
                            projectScale = "7yglcdkBS";
                        } else {
                            projectScale = "other";
                        }
                        objectData.put("field_3wak1__c", projectScale);
//                        objectData.put("field_ysq56__c", projectScale);
                    }
                    String productPlatform = product.getProductPlatform();
                if(!StringUtils.isNullOrEmpty(productPlatform)){
                    List<String> productPlatformList = StringUtil.getProductPlatformList(productPlatform);
                    objectData.put("field_fgLV9__c", productPlatformList);
                }

                String businessType = product.getBusinessType();
                if (null!=businessType){

                    if (product.getBusinessType().equals("1")){
                        businessType="s7I0K2utk";
                    }else if (product.getBusinessType().equals("2")){
                        businessType="2iy2bLhYc";
                    }else if (product.getBusinessType().equals("3")){
                        businessType="tn82Cvd5W";
                    }else if (product.getBusinessType().equals("4")){
                        businessType="hvl5LqPc5";
                    }else if (product.getBusinessType().equals("5")){
                        businessType="pXsSJ3RpN";
                    }else if (product.getBusinessType().equals("6")){
                        businessType="YK93Fhwi0";
                    }else if (product.getBusinessType().equals("7")){
                        businessType="1134nJ2lN";
                    }else {
                        businessType="other";
                    }
                    objectData.put("field_Sprc2__c", businessType);
                }
                    String projectstatus = product.getProjectstatus();
                    if ("1".equals(projectstatus)) {
                        projectstatus = "rixtbvFZx";
                    } else if ("2".equals(projectstatus)) {
                        projectstatus = "2vHH8anm8";
                    } else if ("3".equals(projectstatus)) {
                        projectstatus = "option1";
                    } else if ("4".equals(projectstatus)) {
                        projectstatus = "pdZN7S7gN";
                        LOG.info("项目已验收修改禅道推送状态");
                        int i = iProduct.updateProjectStatus(id);
                        if (i>0){
                            LOG.info("修改禅道推送状态成功"+product.getName());
                        }else {
                            LOG.info("修改禅道推送状态失败"+product.getName());
                        }
                    } else if ("5".equals(projectstatus)) {
                        projectstatus = "b2b71ZK5u";
                    } else if ("6".equals(projectstatus)) {
                        projectstatus = "apJB66nrc";
                    } else if ("7".equals(projectstatus)) {
                        projectstatus = "fS8IDA82v";
                    } else {
                        projectstatus = "other";
                    }

                    objectData.put("_id", crmPid);
                    objectData.put("field_3TN34__c", code);
                    objectData.put("field_AYAPc__c", projectstatus);
                    objectData.put("field_2X7Wv__c", createTime);

                    //根据用户账号查询用户名字
//                    String manageName = product.getPo();
//                     System.out.println(manageName);
//                    User user = iUser.selectByAccount(manageName);
//                    // System.out.println(user.getRealname());
//                    ArrayList<Object> manageNameObjects = new ArrayList<>();
//                    manageNameObjects.add(user.getRealname());
//                    System.out.println("保存项目" + product.getName());
//                    System.out.println(user.getRealname());
//                    String userInfo = GetUserInfo.GetUserId(manageNameObjects, token);
//                    if (userInfo == null) {
//                        LOG.info("获取用户信息失败");
//                       // continue;
//
//                    }else {
//                        // System.out.println(userInfo);
//                        ArrayList<Object> uid = new ArrayList<>();
//                        uid.add(userInfo);
//                        //System.out.println(uid);
//                        objectData.put("field_pwX59__c", uid);
//                    }

                    // System.out.println(userInfo);
//                    ArrayList<Object> uid = new ArrayList<>();
//                    uid.add(userInfo);
//                    //System.out.println(uid);
//                    objectData.put("field_pwX59__c", uid);
                    //设置业务人员
//                    ArrayList<Object> manageNameSa = new ArrayList<>();
//                    manageNameSa.add(product.getSalesman());
//                    String saInfo = GetUserInfo.GetUserId(manageNameSa, token);
//                    if (saInfo == null) {
//                        LOG.info("获取用户信息业务人员是失败，跳过该项目:"+product.getName());
//                        //continue;
//                    }else {
//                        // System.out.println(userInfo);
//                        ArrayList<Object> saInfoid = new ArrayList<>();
//                        saInfoid.add(saInfo);
//                        objectData.put("field_swdR3__c", saInfoid);
//                    }


                    //统计项目工时
                    Double aDouble = 0.00D;
                    List<Effort> efforts = iEffort.selectProduct(productId);
                    if (efforts.size() < 1) {
                        objectData.put("field_02TJl__c", aDouble);
                    } else {
                        Double consumed = iEffort.selectConsumed(productId);
                        aDouble = Double.valueOf(consumed / 8);
                        BigDecimal bg = new BigDecimal(aDouble);
                        double f1 = bg.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                        objectData.put("field_02TJl__c", f1);
                    }

                    /**
                     * 进度(百分比)	禅道回传		百分比		ProjectProgressPercentage	field_42pcI__c
                     * 启动时间	禅道回传		日期		ProjectStartDate	field_fmooS__c
                     * 结束时间	禅道回传		日期		ProjectEndDate	field_1c226__c
                     *
                     */
                    String projectprogresspercentage = product.getProjectprogresspercentage();
                    Double percentage = Double.parseDouble(projectprogresspercentage.replace("%", ""));

                    Date projectstartdate = product.getProjectstartdate();
                    Date projectenddate = product.getProjectenddate();
                    objectData.put("field_42pcI__c", percentage);
                    objectData.put("field_fmooS__c", projectstartdate);
                    objectData.put("field_1c226__c", projectenddate);
                    /**
                     * 软件外包金额	禅道回传		金额		SoftwareAmountOutsource	field_7Gu1n__c
                     * 售前预估工时	新建？传到禅道/统计引用合同工时		数字		SQCost	field_EsBxP__c
                     * 可预见变更	禅道回传		文本		ExpectedChange	field_Lxdfg__c
                     * 可预见变更说明	禅道回传		文本		ExpectedChangeNote	field_x2522__c
                     * 任务实际工时	禅道回传		数字
                     * 需求变更人天	统计属于需求变更的销售订单金额	可以修改	数字
                     * 项目上线时间(计划)	禅道回传		日期		ProjectReleaseDate	field_0gy2e__c
                     * 项目上线时间(实际)	禅道回传		日期		ProjectReleaseDatePlan	field_Jz7qK__c
                     * 项目创建时间	禅道回传		日期		createdDate	create_time
                     * 备注	新建/禅道回传		多行文本	新建字段	remark	field_ScS2r__c
                     * 回传备注	禅道回传		多行文本	新建字段		field_nflsY__c
                     */
                    BigDecimal softwareamountoutsource = product.getSoftwareamountoutsource();
                    String expectedchange = product.getExpectedchange();
                    if ("1".equals(expectedchange)) {
                        expectedchange = "option1";
                    } else if ("2".equals(expectedchange)) {
                        expectedchange = "0Gy8KOcyl";
                    } else {
                        expectedchange = "other";
                    }
                    String expectedchangenote = product.getExpectedchangenote();
                    //可预见变更说明截取
                    if(expectedchangenote.length()>1999){
                        String substring = expectedchangenote.substring(0, 1980);
                        objectData.put("field_x2522__c", substring);
                    }else {
                        objectData.put("field_x2522__c", expectedchangenote);
                    }

                    Date projectreleasedate = product.getProjectreleasedate();
                    Date projectreleasedateplan = product.getProjectreleasedateplan();
                    Date createddate = product.getCreateddate();
                Date projectCompleteDate = product.getProjectCompleteDate();
                String returnRemark = product.getReturnRemark();
                    if(returnRemark.length()>2000){
                        String substring = returnRemark.substring(0, 1990);
                        objectData.put("field_nflsY__c", substring);
                    }else {
                        objectData.put("field_nflsY__c", returnRemark);
                    }
                    objectData.put("field_7Gu1n__c", softwareamountoutsource);
                    objectData.put("field_Lxdfg__c", expectedchange);

                    objectData.put("field_0gy2e__c", projectreleasedate);
                    objectData.put("field_Jz7qK__c", projectreleasedateplan);
                    objectData.put("create_time", createddate);
                   // Date okDate = iAction.selectDateOk(productId);
                    if (null != projectCompleteDate){
                        objectData.put("field_i785j__c", projectCompleteDate.getTime());
                    }
                    Date waitDate = iAction.selectDateWait(productId);
                    if (null != waitDate){
                        objectData.put("field_fhcrZ__c", waitDate.getTime());
                    }
                    //推送实施数据
                    if (!StringUtils.isNullOrEmpty(product.getIsOrNoInstall())){
                         if (product.getIsOrNoInstall().equals("1")){
                            objectData.put("field_IosSr__c", "option1");
                        }else if (product.getIsOrNoInstall().equals("2")){
                            objectData.put("field_IosSr__c", "f1ZEr422m");
                        }else {
                            objectData.put("field_IosSr__c", "other");
                        }

                    }
                /**
                     *
                     * 向crm同步实施数据
                     *
                     *
                     */

//                    通过项目id查询实施填写的项目
//                iInstall.selectByPrimaryKey(id);
//                    PCode实施里面存的项目名字

                    installManage installManage = iInstall.selectByPCode(product.getName());

                    if (null!=installManage) {
                        LOG.info("项目:" + product.getName()+"有实施数据--"+"开始向crm字段赋值");
                        ArrayList<Object> installHeaderObjects = new ArrayList<>();
                        //设置实施负责人
                        String header = installManage.getHeader();
                        if (null!=header&&!header.equals("")){
                            User installHeader = iUser.selectByAccount(header);
                            installHeaderObjects.add(installHeader.getRealname());
                            String installHeaderuser = GetUserInfo.GetUserId(installHeaderObjects, token);
                            if (installHeaderuser == null) {
                                LOG.info("获取实施负责人信息失败，跳过该项目:"+product.getName());

                            }else {

                                ArrayList<Object> installHeadId = new ArrayList<>();
                                installHeadId.add(installHeaderuser);
                                objectData.put("field_b6SpF__c", installHeadId);
                            }
                        }


                        //设置结算方式
                        String settlementtype = installManage.getSettlementtype();
                        if (null!=settlementtype){

                            if (settlementtype.equals("1")){
                                objectData.put("field_r9c81__c", "option1");
                            }else if (settlementtype.equals("2")){
                                objectData.put("field_r9c81__c", "HK7B3jvxB");
                            }else {
                                objectData.put("field_r9c81__c", "other");
                            }
                        }
                        //是否含差旅费
                        String isornottravel = installManage.getIsornottravel();
                        if (null!=isornottravel){
                            if (isornottravel.equals("1")){
                                objectData.put("field_2Slwj__c", "option1");
                            }else if (isornottravel.equals("2")){
                                objectData.put("field_2Slwj__c", "pj2MhG90l");
                            }else {
                                objectData.put("field_2Slwj__c", "other");
                            }
                        }
                        //实施类型
                        String worktype = installManage.getWorktype();
                        if (null!=worktype){
                            if (worktype.equals("1")){
                                objectData.put("field_oE9gQ__c", "703L5qzVm");
                            }else if (worktype.equals("2")){
                                objectData.put("field_oE9gQ__c", "I86G7C6Wb");
                            }else if (worktype.equals("3")){
                                objectData.put("field_oE9gQ__c", "c18xrdstR");
                            } else {
                                objectData.put("field_oE9gQ__c", "other");
                            }
                        }
                        String workway = installManage.getWorkway();
                        if (null!=workway){
                            if (workway.equals("1")){
                                objectData.put("field_382R0__c", "SaikKgU95");
                            }else if (workway.equals("2")){
                                objectData.put("field_382R0__c", "2mSm4gt6w");
                            }else if (workway.equals("3")){
                                objectData.put("field_382R0__c", "c3F3mK1ug");
                            } else {
                                objectData.put("field_382R0__c", "other");
                            }
                        }
                        //差旅费结算方式
                        String travelsettlementway = installManage.getTravelsettlementway();
                        if (null!=travelsettlementway){
                            if (travelsettlementway.equals("1")){
                                objectData.put("field_a8rH9__c", "o8miRcpSY");
                            }else if (travelsettlementway.equals("2")){
                                objectData.put("field_a8rH9__c", "6P0z95ICw");
                            }else {
                                objectData.put("field_a8rH9__c", "other");
                            }

                        }
                        //实施单价（卖价）
                        Double installprice = installManage.getInstallprice();
                        if (null!=installprice){
                            objectData.put("field_RXp5V__c", installprice);
                        }



                        //实施实际开票金额
                        Double installrealityamount = installManage.getInstallrealityamount();
                        if (null!=installrealityamount){
                            objectData.put("field_9A7pb__c", installrealityamount);
                        }


                        /**
                         * 实施变更评估实施差旅费	installChangeTravelAmount	field_12d54__c
                         * 实施变更评估实施天数	installChangeTravelDay	field_w8972__c
                         * 实施变更合同金额	installChangePactAmount	field_EatC7__c
                         * 实施变更实际实施差旅费	总金额installChangeAllAmount	field_bAf4i__c
                         * 实施变更实际实施天数	instChangerealityDay	field_f1C47__c
                         * 需求变更实际人天成本	changeRaelityCost	field_5Ytqs__c
                         */
                        Double installchangetravelamount=0.00;
                        Double installchangetravelday=0.00;
                        Double installchangepactamount=0.00;
                        Double installchangeallamount=0.00;
                        Double instchangerealityday=0.00;
                        Double changeraelitycost=0.00;
                        //需求变更总金额
                        Double intallChangeCostSum=0.00;
                        List<InstallChange> installChanges = iInstallChange.selectByPid(installManage.getId());
                        if (null!=installChanges&&installChanges.size()>0) {
                            for (InstallChange installChange:installChanges) {

                                String installchangetravelamount1 = installChange.getInstallchangetravelamount();
                                if (null!=installchangetravelamount1&&!installchangetravelamount1.equals("")){
                                    installchangetravelamount+= Double.valueOf(installchangetravelamount1);
                                }
                                if (null!=installChange.getInstallchangetravelday()&&!installChange.getInstallchangetravelday().equals("")){
                                    installchangetravelday+=Double.valueOf(installChange.getInstallchangetravelday());
                                }

                                if (null!=installChange.getInstallchangetravelamount()&&!installChange.getInstallchangetravelamount().equals("")){
                                    installchangepactamount+=Double.valueOf(installChange.getInstallchangetravelamount());
                                }

                                if (null!=installChange.getInstallchangeallamount()&&!installChange.getInstallchangeallamount().equals("")){
                                    installchangeallamount+=Double.valueOf(installChange.getInstallchangeallamount());
                                }

                                if (null!=installChange.getInstchangerealityday()&&!installChange.getInstchangerealityday().equals("")){
                                    instchangerealityday+=Double.valueOf(installChange.getInstchangerealityday());
                                }
                                if (null!=installChange.getChangeraelitycost()&&!installChange.getChangeraelitycost().equals("")){
                                    changeraelitycost+=Double.valueOf(installChange.getChangeraelitycost())/installChanges.size();
                                }

                                if(null!=installChange.getInstchangerealityday()&&!installChange.getInstchangerealityday().equals("")
                                        &&null!=installChange.getChangeraelitycost()&&!installChange.getChangeraelitycost().equals("")){

                                    intallChangeCostSum=intallChangeCostSum+Double.valueOf(installChange.getInstchangerealityday())*
                                            Double.valueOf(installChange.getChangeraelitycost());
                                    if (null!=installChange.getInstallchangeallamount()&&!installChange.getInstallchangeallamount().equals("")){
                                        intallChangeCostSum=intallChangeCostSum+Double.valueOf(installChange.getInstallchangeallamount());
                                    }

                                }

                            }
//                            Double installchangetravelamount = installManage.getInstallchangetravelamount();
                            if (null != installchangetravelamount) {

                                objectData.put("field_12d54__c", BigDecimalUtil.mdounle(installchangetravelamount));
                            }
//                            String installchangetravelday = installManage.getInstallchangetravelday();
                            if (null != installchangetravelday) {
                                objectData.put("field_w8972__c", installchangetravelday.toString());
                            }
//                            Double installchangepactamount = installManage.getInstallchangepactamount();
                            if (null != installchangepactamount) {

                                objectData.put("field_EatC7__c",  BigDecimalUtil.mdounle(installchangepactamount));
                            }
//                            Double installchangeallamount = installManage.getInstallchangeallamount();
                            if (null != installchangeallamount) {
//                                Double mdounle = BigDecimalUtil.mdounle(installchangeallamount);

                                objectData.put("field_bAf4i__c",  BigDecimalUtil.mdounle(installchangeallamount));
                            }
//                            String instchangerealityday = installManage.getInstchangerealityday();
                            if (null != instchangerealityday) {

                                objectData.put("field_f1C47__c", instchangerealityday.toString());
                            }
//                            Double changeraelitycost = installManage.getChangeraelitycost();
                            if (null != changeraelitycost) {

                                objectData.put("field_5Ytqs__c", BigDecimalUtil.mdounle(changeraelitycost));
                            }
                        }




                        //售前评估实施差旅费  crm->禅道  项目字段有
                        //售前评估实施天数   crm->禅道  项目字段有

                        //实际实施天数    通过明细算
                        //实际实施成本   通过明细算

                        //实施天数总和
                        Double timeDiffSum=0.0;
                        //实际差旅费总和
                        Double realitysum=0.0;

                        //通过实施id查询实施明细
                        List<installManageDetail> installManageDetails = iInstallDetail.selectByInstallId(installManage.getId());
                        //进场次数	EnterFactoryCount
                        String enterfactorycount = installManage.getEnterfactorycount();
                        if (null!=enterfactorycount){
                            objectData.put("field_psSk4__c", enterfactorycount);
                        }else {
                            objectData.put("field_psSk4__c", 0);
                        }
                        if (installManageDetails!=null&&installManageDetails.size()!=0){

                            //实施总天数

                            //实际实施成本   通过明细算
                            Double intallCostSum=0.00;
                            for (installManageDetail installManageDetail:installManageDetails){

//                                System.out.println(installManageDetail);
//                                Date editeddate = installManageDetail.getDeparturedate();
//
//                                Date entrydate = installManageDetail.getEntrydate();
//                                Integer  timeDiff= DateUtil.daysBetween(editeddate,entrydate);
//                                if (timeDiff==0){
//                                    timeDiff=1;
//                                }
//                                System.out.println(timeDiff);
                                String installDay = installManageDetail.getInstallDay();
                                Double installDays=0.00;
                                if (null!=installDay&&!installDay.equals("")) {
                                     installDays = Double.valueOf(installDay);
                                }
                                //每次天数
                                timeDiffSum+=installDays;
                                System.out.println(timeDiffSum);
                                //实际发生差旅费用
                                Double travelAmount=0.00;
                                String travel = installManageDetail.getTravel();
                                if (null!=travel&&!travel.equals("")) {
                                     travelAmount = Double.valueOf(travel);
                                }
                                realitysum=realitysum+travelAmount;

                                //人天成本	labourcost
                                String labourcost = installManageDetail.getLabourcost();
                                Double everyCost=0.00;
                                if (null!=labourcost&&!labourcost.equals("")) {
                                     everyCost = Double.valueOf(labourcost);
                                }

                                intallCostSum= intallCostSum+ installDays*everyCost+travelAmount;

                            }
                            //实际实施天数    通过明细算

                            objectData.put("field_IO5r8__c",  BigDecimalUtil.mdounle(timeDiffSum+instchangerealityday));
                            //实际实施成本

                            objectData.put("field_74rse__c", BigDecimalUtil.mdounle(intallCostSum+intallChangeCostSum));

                            //实施进度说明	installPalnNote	field_OXVf4__c
                            //实施进度百分比	installPlanPercent	field_YTiU3__c
                            String installpalnnote = installManage.getInstallpalnnote();
                            if (null!=installpalnnote){
                                objectData.put("field_OXVf4__c", installpalnnote);
                            }
                            String installplanpercent = installManage.getInstallplanpercent();
                            if (null!=installplanpercent){
                                Double installPercentage = Double.parseDouble(installplanpercent.replace("%", ""));
                                objectData.put("field_YTiU3__c", installPercentage);
                            }

                            //项目实施状态	state

                            String status = installManage.getStatus();
                            if (null!=status){
                                if (status.equals("1")){
                                    objectData.put("field_15pea__c", "PsKO7zJ4m");
                                }else if (status.equals("2")){
                                    objectData.put("field_15pea__c", "2fipCixcw");
                                }else if (status.equals("3")){
                                    objectData.put("field_15pea__c", "h2ioh1wZA");
                                }else {
                                    objectData.put("field_15pea__c", "other");
                                }
                            }

                            //合同实施实际金额
                            /**
                             * pactRealityAmount	field_IB72E__c
                             * 固定  settlementtype
                             * 是否有差旅费isornottravel
                             * 差旅方式 travelsettlementway
                             * 合同的实施固定费用pactfixedinstallamount
                             *合同的固定差旅费 pactfixedtravelamount
                             * "1、固定费用&是&差旅固定：合同的实施固定费用+合同的固定差旅费
                             * 2、固定费用&是&差旅按时：合同的实施固定费用+实际差旅费（明细之和）
                             * 3、按时费用&是&固定：实际实施天数*实施单价（卖价）+合同的固定差旅费
                             * 4、固定费用&否：合同的实施固定费用
                             * 5、按时费用&否：实际实施天数*实施单价（卖价）
                             * 6、按时费用&是&差旅按时：实际实施天数*实施单价（卖价）+实际差旅费（明细之和）"
                             */



                            Double pactfixedinstallamount = installManage.getPactfixedinstallamount();
                            Double pactfixedtravelamount = installManage.getPactfixedtravelamount();
                            Double sum =0.00;
                            if (settlementtype.equals("1")&&isornottravel.equals("1")&&travelsettlementway.equals("1")){

                                sum=pactfixedinstallamount+pactfixedtravelamount;


                                objectData.put("field_IB72E__c", BigDecimalUtil.mdounle(sum));
                            }else if (settlementtype.equals("1")&&isornottravel.equals("1")&&travelsettlementway.equals("2")){
                                sum=pactfixedinstallamount+realitysum;
                                Double sums = Double.valueOf(BigDecimalUtil.mdounle(sum));
                                objectData.put("field_IB72E__c", sums);
                            }else if (settlementtype.equals("2")&&isornottravel.equals("1")&&travelsettlementway.equals("1")){
                                sum= timeDiffSum*installprice+pactfixedtravelamount;
                                Double sums = Double.valueOf(BigDecimalUtil.mdounle(sum));
                                objectData.put("field_IB72E__c", sums);

                            }else if (settlementtype.equals("1")&&isornottravel.equals("2")){
                                sum= pactfixedinstallamount;
                                Double sums = Double.valueOf(BigDecimalUtil.mdounle(sum));
                                objectData.put("field_IB72E__c", sums);
                            }else if (settlementtype.equals("2")&&isornottravel.equals("2")){
                                sum= timeDiffSum*installprice;
                                Double sums = Double.valueOf(BigDecimalUtil.mdounle(sum));
                                objectData.put("field_IB72E__c", sums);
                            }else if (settlementtype.equals("2")&&isornottravel.equals("1")&&travelsettlementway.equals("2")){
                                sum= timeDiffSum*installprice+realitysum;
                                Double sums = Double.valueOf(BigDecimalUtil.mdounle(sum));
                                objectData.put("field_IB72E__c", sums);
                            }else {
                                Double sums = Double.valueOf(BigDecimalUtil.mdounle(sum));
                                objectData.put("field_IB72E__c", sums);
                            }
                            //通过项目crmid反写合同实施实际金额，实际实施天数，实际实施天数
                            // sum timeDiffSum  intallCostSum

                            int count = iInstall.updateBycrmPid(crmPid, sum,  BigDecimalUtil.mdounle(intallCostSum), timeDiffSum.toString());

                            if (count>0){
                                LOG.info("项目:" + product.getName()+"--反写合同实施实际金额，实际实施天数，实际实施天数成功");
                            }else {
                                LOG.info("项目:" + product.getName()+"--反写合同实施实际金额，实际实施天数，实际实施天数失败");

                            }
                        }

                    }else {
                        LOG.info("项目:" + product.getName()+"无实施数据");
                    }


                    data.put("object_data", objectData);
                    Map<String, Object> stringObjectMap = PushData.PushData(data, token);
                    System.out.println(stringObjectMap);
                    String errorMessage = (String) stringObjectMap.get("errorMessage");
                    if (errorMessage.equals("OK")) {
                        LOG.info("向crm更新项目成功:"+product.getName());
                    } else {
//                        emailUtil.sendMail("向crm推送项目和实施数据失败--"+product.getName()+"--crm返回失败原因："+errorMessage);
                        LOG.info("向crm更新项目失败"+product.getName()+"--crm返回失败原因：" + errorMessage);
                    }
//                        }

//                }
            }
        }
    }

    @Override
    @Transactional
    public void getUpdateData() throws Exception {
        LOG.info("开始修改禅道项目，金额信息");
        List<Product> productList = iProduct.selectPush();
        BigDecimal defaultValue = new BigDecimal(0.0);
        Map<String, Object> token = GetToken.getToken();
        if (productList!=null && productList.size()!=0) {
            for (Product products : productList) {
                LOG.info("开始修改项目:"+products.getName());
                String crmPid = products.getCrmPid();
                Map<String, Object> projectInfo = GetProjectInfo.getProjectInfoById(crmPid, token);
                if (!projectInfo.get("errorMessage").equals("OK")){
                    continue;
                }
                Map<String, Object> project = (Map<String, Object>) projectInfo.get("data");
                System.out.println(project);
                Product productUpdate = new Product();
                //获取传入禅道备注

                productUpdate.setCrmPid(crmPid);
//                Map<String, Object> token = GetToken.getToken();
                String corpAccessToken = (String) token.get("corpAccessToken");
                if (null ==project.get("field_pwX59__c")){
                   continue;
                }
                List<Object> ownerKey = (List<Object>) project.get("field_pwX59__c");
                //获取项目经理人
                Map<String, Object> owner = GetUserInfo.GetUserInfo(ownerKey, corpAccessToken);
                if (owner.isEmpty()){
                    continue;
                }
                User manageNames=null;
                if (null!=owner.get("name")) {
                    String ownerName = (String) owner.get("name");

                    System.out.println(ownerName);
                    //通过名字查询用户账户
                    manageNames = iUser.selectByName(ownerName);
                    if(manageNames ==null){
                        emailUtil.sendMailMe("每日发送邮件报错---项目经理在禅道不存在:"+ownerName );
                        continue;
                    }
                    LOG.info("manageNames:"+manageNames.getAccount());
                    if (null!=manageNames.getAccount()){
                        productUpdate.setPo(manageNames.getAccount());
                    }
                    if (null!=manageNames.getAccount()) {
//                    System.out.println("通过名字查询用户账户");
                        if (null==products.getPo()|| products.getPo().equals("")){
                            this.addUserView(crmPid,manageNames);

                        }else if (!products.getPo().equals("")&&!manageNames.getAccount().equals(products.getPo())){

                            productUpdate.setPo(manageNames.getAccount());
                            LOG.info("高管视图新增成功,开始给项目经理发送邮件");
                            MailBean mailBean = new MailBean();
                            mailBean.setProjectName(productUpdate.getName());
                            mailBean.setReceiptPeople(manageNames.getEmail());
                            mailBean.setTransform(products.getPo());

                            //添加修改项目经理
                            mailBean.setProjectStatus("XG");
                            mailBean.setRealName(manageNames.getRealname());
                            iMail.projectAddRemind(mailBean);
                           this.updateProductProjectData(products,manageNames);
                        }
                    }
//                    User manageName = iUser.selectByName(ownerName);

                }
                //获取客户名称里的负责人
//                Map<String, Object> stringObjectMap = GetCustomerInfo.GetCustomerInfo(project.get("field_g8WuI__c").toString(), token);
//
//                Map<String, Object> customerInfo = ( Map<String, Object>)stringObjectMap.get("data");
//                //项目里的客户
//                List<Object> lastModifiedByKey = (List<Object>)customerInfo.get("owner");
//                //获取token值
//                String corpAccessToken = (String) token.get("corpAccessToken");
//                //获取业务人员姓名
//                Map<String, Object> user = GetUserInfo.GetUserInfo(lastModifiedByKey, corpAccessToken);
//                String userName = (String) user.get("name");
//                System.out.println("获取业务人员:"+userName);
//                productUpdate.setSalesman(userName);

                //获取销售订单的数量
                //获取是否提前立项
                //获取销售订单的数量
//                project.get("field_4DdEm__c").toString()
//                Map<String, Object> stringObjectMap = GetCustomerInfo.GetCustomerInfo(project.get("field_g8WuI__c").toString(), token);
//                System.out.println(stringObjectMap);

                if (null != project.get("field_f517f__c")) {
                    String projectoutType = project.get("field_f517f__c").toString();
                    if (projectoutType.equals("5x1mgB8ra")){
                        productUpdate.setProjectoutType("1");
                    }else if (projectoutType.equals("ckut3yZfM")){
                        productUpdate.setProjectoutType("2");
                    }else if (projectoutType.equals("brhn1AoiQ")){
                        productUpdate.setProjectoutType("3");
                    }else if (projectoutType.equals("Y4B19C3p1")){
                        productUpdate.setProjectoutType("4");
                    }else {
                        productUpdate.setCode("");
                    }
                } else {
                    productUpdate.setCode("");
                }

                if (null!=project.get("field_15Rv8__c")) {
                    String isAdvances = project.get("field_15Rv8__c").toString();
                    if (isAdvances.equals("option1")) {
                        productUpdate.setIsOrNotStart("2");
                    } else if (isAdvances.equals("S1B1uuJ1p")) {
                        productUpdate.setIsOrNotStart("1");
                    }
                }
                String projectstatus = products.getProjectstatus();
                if (projectstatus.equals("8")){
                    String nums = project.get("field_4DdEm__c").toString();
                    Integer orderNum = Integer.valueOf(nums);
                    String  isAdvance = project.get("field_15Rv8__c").toString();
                    String  isStart="";
                    if (isAdvance.equals("option1")){
                        productUpdate.setIsOrNotStart("2");
                        isStart="2";
                    }else if(isAdvance.equals("S1B1uuJ1p")){
                        productUpdate.setIsOrNotStart("1");
                        isStart="1";
                    }
                    if (isAdvance.equals("option1")&&orderNum==0){
                        productUpdate.setProjectstatus("8");
                        //closed
                        productUpdate.setStatus("closed");
                    }else {
                        productUpdate.setProjectstatus("7");
                        productUpdate.setStatus("normal");
                        //修改迭代状态为进行中
                        int i = projectMapper.updateByProductId(products.getId().toString());
                        if (i>0){
//                                LOG.info("修改迭代状态成功");
                        }else {
                            LOG.info("修改迭代状态失败");
                        }
                        //如果还是状态还是8就不修改 如果状态修改了，就修改
                        //先查询是否存在
                        unclaimedProject unclaimedProject = iUnclaimedProject.selectByPid(products.getId().toString());
                        if (null!=unclaimedProject){
                            int count = iUnclaimedProject.updateStatusByPid(products.getId().toString(), "7", isStart,"尽快领取");
                            if (count>0){

                                LOG.info("待领取项目修改状态成功");
                                MailBean mailBean = new MailBean();
                                if (null!=manageNames.getAccount()){

                                    User manageName = iUser.selectByAccount(manageNames.getAccount());
                                    mailBean.setProjectName(products.getName());
                                    mailBean.setReceiptPeople(manageName.getEmail());
                                    mailBean.setProjectStatus("7");
                                    mailBean.setTransform("Y");
                                    mailBean.setRealName(manageName.getRealname());
                                    iMail.projectAddRemind(mailBean);
                                    LOG.info("项目经理发送邮件成功");
                                }
                            }else {
                                LOG.info("待领取项目修改状态失败");
                            }

                        }
                        }
                }else {
                    productUpdate.setProjectstatus(projectstatus);
                    productUpdate.setStatus("normal");
                }


                if(null!=project.get("field_ScS2r__c")){
                    productUpdate.setRemark(project.get("field_ScS2r__c").toString());
                }else {
                    productUpdate.setRemark("");
                }
                productUpdate.setRemark("");
                System.out.println(crmPid);
                //低利率
                if ("option1".equals(project.get("field_uWq15__c").toString())){
                    productUpdate.setLowprofitauditstatus("1");
                    //ProfitControlLine 指定利润率控制线 空白
                    productUpdate.setProfitcontrolline("");
                }else if ("zwSS34hu9".equals(project.get("field_uWq15__c").toString())){
                    productUpdate.setLowprofitauditstatus("2");
                    productUpdate.setProfitcontrolline("");
                }else if ("o1Nc5o3Xb".equals(project.get("field_uWq15__c").toString())){
                    productUpdate.setLowprofitauditstatus("3");
                    if (null!=project.get("field_Fkrd7__c")){
                        productUpdate.setProfitcontrolline(project.get("field_Fkrd7__c").toString());
                    }else {
                        productUpdate.setProfitcontrolline("");
                    }
                }else if ("SqzxbPCaq".equals(project.get("field_uWq15__c").toString())){
                    productUpdate.setLowprofitauditstatus("4");
                    productUpdate.setProfitcontrolline("");
                }else {
                    productUpdate.setLowprofitauditstatus("5");
                    productUpdate.setProfitcontrolline("");
                }
                //软件变更金额
                if (null != project.get("field_IbuIZ__c")) {
                    BigDecimal softwareChange = BigDecimalUtil.getBigDecimal(project.get("field_IbuIZ__c").toString());
                    productUpdate.setSoftwareChangeAmount(softwareChange);
                } else {
                    productUpdate.setSoftwareChangeAmount(defaultValue);
                }

                if (null != project.get("field_5Ytqs__c")) {
                    BigDecimal IntegrateChange = BigDecimalUtil.getBigDecimal(project.get("field_5Ytqs__c").toString());
                    //实施变更金额IntegrateChangeAmount
                    productUpdate.setIntegrateChangeAmount(IntegrateChange);
                } else {
                    productUpdate.setIntegrateChangeAmount(defaultValue);
                }
                //项目实施金额
                if (null != project.get("field_u5meY__c")) {
                    BigDecimal t = BigDecimalUtil.getBigDecimal(project.get("field_u5meY__c").toString());
                    productUpdate.setIntegrateamount(t);
                } else {
                    productUpdate.setIntegrateamount(defaultValue);
                }
                //项目软件金额
                if (null != project.get("field_6K840__c")) {
                    BigDecimal software = BigDecimalUtil.getBigDecimal(project.get("field_6K840__c").toString());
                    productUpdate.setSoftwareamount(software);
                } else {
                    productUpdate.setSoftwareamount(defaultValue);
                }

                //售前预估总工时
//                System.out.println(project.get("field_ysq56__c"));
//                System.out.println(products.getId());
                if (null != project.get("field_ysq56__c")) {
                    Float sqcost = Float.valueOf(project.get("field_ysq56__c").toString());
                    DecimalFormat abc = new DecimalFormat("0.00");

                    productUpdate.setSqcost(Float.valueOf(abc.format(sqcost)));
                    if (0<=sqcost&&sqcost<=10){
                        productUpdate.setProjectScale("1");
                    }else if (11<=sqcost&&sqcost<=50){
                        productUpdate.setProjectScale("2");
                    }else if (51<=sqcost&&sqcost<=150){
                        productUpdate.setProjectScale("3");
                    }else if (151<=sqcost){
                        productUpdate.setProjectScale("4");
                    }
                } else {
                    productUpdate.setSqcost(0.0F);
                }

                //售前预估(追溯)，售前预估(营销)。
                if (null != project.get("field_m5OrN__c")) {
                    Float sqyxcost = Float.valueOf(project.get("field_m5OrN__c").toString());
                    productUpdate.setSQYXCost(sqyxcost);
                } else {
                    productUpdate.setSQYXCost(0.0F);
                }

                if (null != project.get("field_A4a22__c")) {
                    Float sqzscost = Float.valueOf(project.get("field_A4a22__c").toString());
                    productUpdate.setSQZSCost(sqzscost);
                } else {
                    productUpdate.setSQZSCost(0.0F);
                }

                //售前预估集成    售前预估差旅费
                if (null != project.get("field_22312__c")) {
                    Float sqjccost = Float.valueOf(project.get("field_22312__c").toString());
                    productUpdate.setSQJCCost(sqjccost);
                } else {
                    productUpdate.setSQJCCost(0F);
                }

                if (null != project.get("field_ssDd1__c")) {
                    Float sqinstallcost = Float.valueOf(project.get("field_ssDd1__c").toString());
                    productUpdate.setSQInstallAmount(sqinstallcost);
                } else {
                    productUpdate.setSQInstallAmount(0F);
                }
                //field_L47Ul__c  项目总金额

                if (null != project.get("field_L47Ul__c")) {
                    BigDecimal price = BigDecimalUtil.getBigDecimal(project.get("field_L47Ul__c").toString());

                    productUpdate.setProjectprice(price);
                } else {
                    productUpdate.setProjectprice(defaultValue);
                }
                //demandChange  需求变更人天 field_3y5sU__c
                if (null != project.get("field_3y5sU__c")) {
                    Float demandChange = Float.valueOf(project.get("field_3y5sU__c").toString());
                    //System.out.println(demandChange);
                    productUpdate.setDemandChange(demandChange);
                } else {
                    productUpdate.setDemandChange(0F);
                }
                //硬件金额
                if (null != project.get("field_49PzK__c")){
                    BigDecimal hardwareamount = BigDecimalUtil.getBigDecimal(project.get("field_49PzK__c").toString());
                    productUpdate.setHardwareamount(hardwareamount);
                }else {
                    productUpdate.setHardwareamount(defaultValue);
                }
                //服务金额
                if (null!=project.get("field_MC5eu__c")){
                    BigDecimal serviceAmount= BigDecimalUtil.getBigDecimal(project.get("field_MC5eu__c").toString());
                    productUpdate.setServiceamount(serviceAmount);
                }else {
                    productUpdate.setServiceamount(defaultValue);
                }

                int i = iProduct.updateByCrmPid(productUpdate);
                if (i>0){
//                    LOG.info("向禅道更新金额成功:"+products.getName());
                }else {
                    LOG.info("向禅道更新金额失败:"+products.getName());
                }

            }
        }
    }

    @Override
    public void UpdateCrmInstallData() throws Exception {

        LOG.info("开始想crm推送数据");
        Map<String, Object> token = GetToken.getToken();
        List<Product> products = iProduct.selectPush();
        if (products!=null && products.size()!=0) {
            for (Product product : products) {

                LOG.info("获取到最新修改工时的项目:"+product.getName());
                Map<String, Object> data = new HashMap<>();
                Map<Object, Object> objectData = new HashMap<>();
                objectData.put("dataObjectApiName", "object_h249C__c");
                String crmPid = product.getCrmPid();

                /**
                 *
                 * 向crm同步实施数据
                 *
                 *
                 */

                //通过项目id查询实施填写的项目
//                iInstall.selectByPrimaryKey(id);
                //PCode实施里面存的项目名字

                installManage installManage = iInstall.selectByPCode(product.getName());

                if (null!=installManage) {
                    LOG.info("项目:" + product.getName()+"有实施数据--"+"开始向crm字段赋值");
                    ArrayList<Object> installHeaderObjects = new ArrayList<>();
                    //设置实施负责人
                    String header = installManage.getHeader();
                    if (null!=header&&!header.equals("")){
                        User installHeader = iUser.selectByAccount(header);
                        installHeaderObjects.add(installHeader.getRealname());
                        String installHeaderuser = GetUserInfo.GetUserId(installHeaderObjects, token);
                        if (installHeaderuser == null) {
                            LOG.info("获取实施负责人信息失败，跳过该项目:"+product.getName());

                        }else {

                            ArrayList<Object> installHeadId = new ArrayList<>();
                            installHeadId.add(installHeaderuser);
                            objectData.put("field_b6SpF__c", installHeadId);
                        }
                    }


                    //设置结算方式
                    String settlementtype = installManage.getSettlementtype();
                    if (null!=settlementtype){

                        if (settlementtype.equals("1")){
                            objectData.put("field_r9c81__c", "option1");
                        }else if (settlementtype.equals("2")){
                            objectData.put("field_r9c81__c", "HK7B3jvxB");
                        }else {
                            objectData.put("field_r9c81__c", "other");
                        }
                    }
                    //是否含差旅费
                    String isornottravel = installManage.getIsornottravel();
                    if (null!=isornottravel){
                        if (isornottravel.equals("1")){
                            objectData.put("field_2Slwj__c", "option1");
                        }else if (isornottravel.equals("2")){
                            objectData.put("field_2Slwj__c", "pj2MhG90l");
                        }else {
                            objectData.put("field_2Slwj__c", "other");
                        }
                    }
                    //实施类型
                    String worktype = installManage.getWorktype();
                    if (null!=worktype){
                        if (worktype.equals("1")){
                            objectData.put("field_oE9gQ__c", "703L5qzVm");
                        }else if (worktype.equals("2")){
                            objectData.put("field_oE9gQ__c", "I86G7C6Wb");
                        }else if (worktype.equals("3")){
                            objectData.put("field_oE9gQ__c", "c18xrdstR");
                        } else {
                            objectData.put("field_oE9gQ__c", "other");
                        }
                    }
                    String workway = installManage.getWorkway();
                    if (null!=workway){
                        if (workway.equals("1")){
                            objectData.put("field_382R0__c", "SaikKgU95");
                        }else if (workway.equals("2")){
                            objectData.put("field_382R0__c", "2mSm4gt6w");
                        }else if (workway.equals("3")){
                            objectData.put("field_382R0__c", "c3F3mK1ug");
                        } else {
                            objectData.put("field_382R0__c", "other");
                        }
                    }
                    //差旅费结算方式
                    String travelsettlementway = installManage.getTravelsettlementway();
                    if (null!=travelsettlementway){
                        if (travelsettlementway.equals("1")){
                            objectData.put("field_a8rH9__c", "o8miRcpSY");
                        }else if (travelsettlementway.equals("2")){
                            objectData.put("field_a8rH9__c", "6P0z95ICw");
                        }else {
                            objectData.put("field_a8rH9__c", "other");
                        }

                    }
                    //实施单价（卖价）
                    Double installprice = installManage.getInstallprice();
                    if (null!=installprice){
                        objectData.put("field_RXp5V__c", installprice);
                    }



                    //实施实际开票金额
                    Double installrealityamount = installManage.getInstallrealityamount();
                    if (null!=installrealityamount){
                        objectData.put("field_9A7pb__c", installrealityamount);
                    }


                    /**
                     * 实施变更评估实施差旅费	installChangeTravelAmount	field_12d54__c
                     * 实施变更评估实施天数	installChangeTravelDay	field_w8972__c
                     * 实施变更合同金额	installChangePactAmount	field_EatC7__c
                     * 实施变更实际实施差旅费	总金额installChangeAllAmount	field_bAf4i__c
                     * 实施变更实际实施天数	instChangerealityDay	field_f1C47__c
                     * 需求变更实际人天成本	changeRaelityCost	field_5Ytqs__c
                     */
                    Double installchangetravelamount=0.00;
                    Double installchangetravelday=0.00;
                    Double installchangepactamount=0.00;
                    Double installchangeallamount=0.00;
                    Double instchangerealityday=0.00;
                    Double changeraelitycost=0.00;
                    //需求变更总金额
                    Double intallChangeCostSum=0.00;
                    List<InstallChange> installChanges = iInstallChange.selectByPid(installManage.getId());
                    if (null!=installChanges&&installChanges.size()>0) {
                        for (InstallChange installChange:installChanges) {

                            String installchangetravelamount1 = installChange.getInstallchangetravelamount();
                            if (null!=installchangetravelamount1&&!installchangetravelamount1.equals("")){
                                installchangetravelamount+= Double.valueOf(installchangetravelamount1);
                            }
                            if (null!=installChange.getInstallchangetravelday()&&!installChange.getInstallchangetravelday().equals("")){
                                installchangetravelday+=Double.valueOf(installChange.getInstallchangetravelday());
                            }

                            if (null!=installChange.getInstallchangetravelamount()&&!installChange.getInstallchangetravelamount().equals("")){
                                installchangepactamount+=Double.valueOf(installChange.getInstallchangetravelamount());
                            }

                            if (null!=installChange.getInstallchangeallamount()&&!installChange.getInstallchangeallamount().equals("")){
                                installchangeallamount+=Double.valueOf(installChange.getInstallchangeallamount());
                            }

                            if (null!=installChange.getInstchangerealityday()&&!installChange.getInstchangerealityday().equals("")){
                                instchangerealityday+=Double.valueOf(installChange.getInstchangerealityday());
                            }
                            if (null!=installChange.getChangeraelitycost()&&!installChange.getChangeraelitycost().equals("")){
                                changeraelitycost+=Double.valueOf(installChange.getChangeraelitycost())/installChanges.size();
                            }

                            if(null!=installChange.getInstchangerealityday()&&!installChange.getInstchangerealityday().equals("")
                                    &&null!=installChange.getChangeraelitycost()&&!installChange.getChangeraelitycost().equals("")){

                                intallChangeCostSum=intallChangeCostSum+Double.valueOf(installChange.getInstchangerealityday())*
                                        Double.valueOf(installChange.getChangeraelitycost());
                                if (null!=installChange.getInstallchangeallamount()&&!installChange.getInstallchangeallamount().equals("")){
                                    intallChangeCostSum=intallChangeCostSum+Double.valueOf(installChange.getInstallchangeallamount());
                                }

                            }

                        }
//                            Double installchangetravelamount = installManage.getInstallchangetravelamount();
                        if (null != installchangetravelamount) {

                            objectData.put("field_12d54__c", BigDecimalUtil.mdounle(installchangetravelamount));
                        }
//                            String installchangetravelday = installManage.getInstallchangetravelday();
                        if (null != installchangetravelday) {
                            objectData.put("field_w8972__c", installchangetravelday.toString());
                        }
//                            Double installchangepactamount = installManage.getInstallchangepactamount();
                        if (null != installchangepactamount) {

                            objectData.put("field_EatC7__c",  BigDecimalUtil.mdounle(installchangepactamount));
                        }
//                            Double installchangeallamount = installManage.getInstallchangeallamount();
                        if (null != installchangeallamount) {
//                                Double mdounle = BigDecimalUtil.mdounle(installchangeallamount);

                            objectData.put("field_bAf4i__c",  BigDecimalUtil.mdounle(installchangeallamount));
                        }
//                            String instchangerealityday = installManage.getInstchangerealityday();
                        if (null != instchangerealityday) {

                            objectData.put("field_f1C47__c", instchangerealityday.toString());
                        }
//                            Double changeraelitycost = installManage.getChangeraelitycost();
                        if (null != changeraelitycost) {

                            objectData.put("field_5Ytqs__c", BigDecimalUtil.mdounle(changeraelitycost));
                        }
                    }


                    //售前评估实施差旅费  crm->禅道  项目字段有
                    //实际实施成本   通过明细算

                    //实施天数总和
                    Double timeDiffSum=0.0;
                    //实际差旅费总和
                    Double realitysum=0.0;

                    //通过实施id查询实施明细
                    List<installManageDetail> installManageDetails = iInstallDetail.selectByInstallId(installManage.getId());
                    //进场次数	EnterFactoryCount
                    String enterfactorycount = installManage.getEnterfactorycount();
                    if (null!=enterfactorycount){
                        objectData.put("field_psSk4__c", enterfactorycount);
                    }else {
                        objectData.put("field_psSk4__c", 0);
                    }
                    if (installManageDetails!=null&&installManageDetails.size()!=0){

                        //实施总天数

                        //实际实施成本   通过明细算
                        Double intallCostSum=0.00;
                        for (installManageDetail installManageDetail:installManageDetails){


                            String installDay = installManageDetail.getInstallDay();
                            Double installDays=0.00;
                            if (null!=installDay&&!installDay.equals("")) {
                                installDays = Double.valueOf(installDay);
                            }
                            //每次天数
                            timeDiffSum+=installDays;
                            System.out.println(timeDiffSum);
                            //实际发生差旅费用
                            Double travelAmount=0.00;
                            String travel = installManageDetail.getTravel();
                            if (null!=travel&&!travel.equals("")) {
                                travelAmount = Double.valueOf(travel);
                            }
                            realitysum=realitysum+travelAmount;

                            //人天成本	labourcost
                            String labourcost = installManageDetail.getLabourcost();
                            Double everyCost=0.00;
                            if (null!=labourcost&&!labourcost.equals("")) {
                                everyCost = Double.valueOf(labourcost);
                            }

                            intallCostSum= intallCostSum+ installDays*everyCost+travelAmount;

                        }
                        //实际实施天数    通过明细算

                        objectData.put("field_IO5r8__c",  BigDecimalUtil.mdounle(timeDiffSum+instchangerealityday));
                        //实际实施成本

                        objectData.put("field_74rse__c", BigDecimalUtil.mdounle(intallCostSum+intallChangeCostSum));

                        //实施进度说明	installPalnNote	field_OXVf4__c
                        //实施进度百分比	installPlanPercent	field_YTiU3__c
                        String installpalnnote = installManage.getInstallpalnnote();
                        if (null!=installpalnnote){
                            objectData.put("field_OXVf4__c", installpalnnote);
                        }
                        String installplanpercent = installManage.getInstallplanpercent();
                        if (null!=installplanpercent){
                            Double installPercentage = Double.parseDouble(installplanpercent.replace("%", ""));
                            objectData.put("field_YTiU3__c", installPercentage);
                        }

                        //项目实施状态	state

                        String status = installManage.getStatus();
                        if (null!=status){
                            if (status.equals("1")){
                                objectData.put("field_15pea__c", "PsKO7zJ4m");
                            }else if (status.equals("2")){
                                objectData.put("field_15pea__c", "2fipCixcw");
                            }else if (status.equals("3")){
                                objectData.put("field_15pea__c", "h2ioh1wZA");
                            }else {
                                objectData.put("field_15pea__c", "other");
                            }
                        }

                        //合同实施实际金额
                        /**
                         * pactRealityAmount	field_IB72E__c
                         * 固定  settlementtype
                         * 是否有差旅费isornottravel
                         * 差旅方式 travelsettlementway
                         * 合同的实施固定费用pactfixedinstallamount
                         *合同的固定差旅费 pactfixedtravelamount
                         * "1、固定费用&是&差旅固定：合同的实施固定费用+合同的固定差旅费
                         * 2、固定费用&是&差旅按时：合同的实施固定费用+实际差旅费（明细之和）
                         * 3、按时费用&是&固定：实际实施天数*实施单价（卖价）+合同的固定差旅费
                         * 4、固定费用&否：合同的实施固定费用
                         * 5、按时费用&否：实际实施天数*实施单价（卖价）
                         * 6、按时费用&是&差旅按时：实际实施天数*实施单价（卖价）+实际差旅费（明细之和）"
                         */



                        Double pactfixedinstallamount = installManage.getPactfixedinstallamount();
                        Double pactfixedtravelamount = installManage.getPactfixedtravelamount();
                        Double sum =0.00;
                        if (settlementtype.equals("1")&&isornottravel.equals("1")&&travelsettlementway.equals("1")){

                            sum=pactfixedinstallamount+pactfixedtravelamount;


                            objectData.put("field_IB72E__c", BigDecimalUtil.mdounle(sum));
                        }else if (settlementtype.equals("1")&&isornottravel.equals("1")&&travelsettlementway.equals("2")){
                            sum=pactfixedinstallamount+realitysum;
                            Double sums = Double.valueOf(BigDecimalUtil.mdounle(sum));
                            objectData.put("field_IB72E__c", sums);
                        }else if (settlementtype.equals("2")&&isornottravel.equals("1")&&travelsettlementway.equals("1")){
                            sum= timeDiffSum*installprice+pactfixedtravelamount;
                            Double sums = Double.valueOf(BigDecimalUtil.mdounle(sum));
                            objectData.put("field_IB72E__c", sums);

                        }else if (settlementtype.equals("1")&&isornottravel.equals("2")){
                            sum= pactfixedinstallamount;
                            Double sums = Double.valueOf(BigDecimalUtil.mdounle(sum));
                            objectData.put("field_IB72E__c", sums);
                        }else if (settlementtype.equals("2")&&isornottravel.equals("2")){
                            sum= timeDiffSum*installprice;
                            Double sums = Double.valueOf(BigDecimalUtil.mdounle(sum));
                            objectData.put("field_IB72E__c", sums);
                        }else if (settlementtype.equals("2")&&isornottravel.equals("1")&&travelsettlementway.equals("2")){
                            sum= timeDiffSum*installprice+realitysum;
                            Double sums = Double.valueOf(BigDecimalUtil.mdounle(sum));
                            objectData.put("field_IB72E__c", sums);
                        }else {
                            Double sums = Double.valueOf(BigDecimalUtil.mdounle(sum));
                            objectData.put("field_IB72E__c", sums);
                        }
                        //通过项目crmid反写合同实施实际金额，实际实施天数，实际实施天数
                        // sum timeDiffSum  intallCostSum

                        int count = iInstall.updateBycrmPid(crmPid, sum,  BigDecimalUtil.mdounle(intallCostSum), timeDiffSum.toString());

                        if (count>0){
//                            LOG.info("项目:" + product.getName()+"--反写合同实施实际金额，实际实施天数，实际实施天数成功");
                        }else {
                            LOG.info("项目:" + product.getName()+"--反写合同实施实际金额，实际实施天数，实际实施天数失败");

                        }
                    }

                }else {
                    LOG.info("项目:" + product.getName()+"无实施数据");
                }


                data.put("object_data", objectData);
                Map<String, Object> stringObjectMap = PushData.PushData(data, token);
                System.out.println(stringObjectMap);
                String errorMessage = (String) stringObjectMap.get("errorMessage");
                if (errorMessage.equals("OK")) {
//                    LOG.info("向crm更新项目成功:"+product.getName());
                } else {
//                    emailUtil.sendMail("向crm推送项目和实施数据失败--"+product.getName()+"--crm返回失败原因："+errorMessage);
                    LOG.info("向crm更新项目失败"+product.getName()+"--crm返回失败原因：" + errorMessage);
                }
//                        }

//                }
            }
        }

    }

    @Override
    public void getDatabyName() throws Exception {
        List<Product> productList = iProduct.selectNotCrmId();
        Map<String, Object> token = GetToken.getToken();
        if (productList!=null && productList.size()!=0) {
            for (Product products : productList) {
                String name = products.getName();
                Map<String, Object> stringObjectMap = GetProjectInfo.GetNoCrmPidByName(token, name);
                System.out.println(stringObjectMap);
                String errorMessage = (String)stringObjectMap.get("errorMessage");
                if ("OK".equals(errorMessage)) {
                    Map<String, Object> data = (Map<String, Object>)stringObjectMap.get("data");
                    List<Map<String, Object>> dataList =( List<Map<String, Object>>) data.get("dataList");
                    if (dataList!=null && dataList.size()!=0){
                        for ( Map<String, Object> project :dataList) {
                           String  id = project.get("_id").toString();
                            System.out.println(id);

                            int i = iProduct.updateProjectcrmId(products.getId(), id);
                            if (i>0){
                                System.out.println("修改成功");
                            }else {
                                System.out.println("修改失败");
                            }
                        }
                    }
                }
            }
        }
    }

    private void addUserView(String crmPid, User manageName) {
        if (manageName==null){
            return;
        }
        Product productGetId= iProduct.selectByCrmPid(crmPid);
        UserView userView = iUserView.selectByAccount(manageName.getAccount());
        if (productGetId != null && userView != null) {
            int project = this.createProject(productGetId,manageName);
            UserView userView1 = new UserView();
            Integer id = productGetId.getId();
            String productsView = userView.getProducts();
            String projectsView = userView.getProjects();
            String newProductsView = productsView + "," + id;
            String newProjectsView = projectsView + "," + project;

            userView1.setAccount(manageName.getAccount());
            userView1.setProducts(newProductsView);
            userView1.setProjects(newProjectsView);
            int count = iUserView.updateProducts(userView1);
            if (count > 0) {
                LOG.info("项目经理增加项目视图成功");
            } else {
                LOG.info("项目经理增加项目视图失败");
                int re = iUserView.updateProducts(userView1);
                if (re > 0) {
                    LOG.info("再次增加项目经理增加项目视图成功");
                } else {
                    LOG.info("再次增加项目经理增加项目视图失败");
                }
            }


//            LOG.info("开始获取高管列表");
            List<userGroup> userGroups = iUserGroup.selectAll();
//            LOG.info("获取高层账户:" + userGroups);
            for (userGroup userList : userGroups) {
//                LOG.info("给高管增加项目视图：" + userList.getAccount());
                UserView userViewManage = iUserView.selectByAccount(userList.getAccount());
                String productsManage = userViewManage.getProducts();
                String projects = userViewManage.getProjects();
                String newProjects= projects+","+project;
                String newProductsViewManage = productsManage + "," + id;
                userView1.setAccount(userList.getAccount());
                userView1.setProjects(newProjects);
                userView1.setProducts(newProductsViewManage);
                iUserView.updateProducts(userView1);
            }

            Date date = new Date();
            //向待领取表插入待领取项目
            unclaimedProject unclaimedProject = new unclaimedProject();
            unclaimedProject.setName(productGetId.getName());
            unclaimedProject.setPid(productGetId.getId().toString());
            unclaimedProject.setCreateddate(date);
            unclaimedProject.setPo(manageName.getRealname());
            unclaimedProject.setSalesman(productGetId.getSalesman());
            unclaimedProject.setTime(date);

            unclaimedProject.setDeleted("0");
            unclaimedProject.setStatus(productGetId.getProjectstatus());
            if (productGetId.getProjectstatus().equals("7")){
                unclaimedProject.setNote("尽快领取");
            }else if (productGetId.getProjectstatus().equals("8")){
                unclaimedProject.setNote("未下销售单,未提前启动,先不执行");
            }
            if (productGetId.getIsOrNotStart().equals("2")){
                unclaimedProject.setIsOrNotStart("2");
            }else if (productGetId.getIsOrNotStart().equals("1")){
                unclaimedProject.setIsOrNotStart("1");
            }



            int insert = iUnclaimedProject.insert(unclaimedProject);
            if (insert>0){
                LOG.info("待领取项目插入成功");
                LOG.info("高管视图新增成功,开始给项目经理发送邮件");
                MailBean mailBean = new MailBean();
                mailBean.setProjectName(productGetId.getName());
                mailBean.setReceiptPeople(manageName.getEmail());
                mailBean.setProjectStatus(productGetId.getProjectstatus());
                mailBean.setTransform("N");
                mailBean.setRealName(manageName.getRealname());
                iMail.projectAddRemind(mailBean);
                LOG.info("项目经理发送邮件成功");
            }else {
                LOG.info("待领取项目插入成功");
            }
            //修改项目经理
           // iProduct.updatePoId(manageName.getAccount(),id);
        }
    }
    private int createProject(Product productGetId,User manageName){
        Date date = new Date();
        String projectName = productGetId.getName()+"-1";
        String projectCode = productGetId.getCode()+"-1";
        Project project = new Project();
        project.setPo(manageName.getAccount());
        project.setRelationproject(productGetId.getId().toString());
        project.setName(projectName);
        project.setCode(projectCode);
        project.setType("sprint");
        project.setDeleted("1");
        project.setOpeneddate(date);
        project.setTeam(productGetId.getName()+"团队");
        project.setAcl("custom");
        project.setWhitelist("1,9");
        project.setPri("1");
        project.setStatge("1");
        project.setPm(manageName.getAccount());
        project.setCatid(0);
        project.setOpenedversion("biz4.0.4");
        project.setStatus("doing");

        int order = projectMapper.selectOrder();
        project.setOrder(order*5+5);
        int insert = projectMapper.insert(project);
        if (insert>0){
            LOG.info("新建迭代创建成功");
            List<Project> projects = projectMapper.selectByProductId(productGetId.getId());
            for (Project project1:projects) {
                //项目迭代新增关联
                ProjectProduct projectProduct = new ProjectProduct();
                projectProduct.setProject(project1.getId());
                projectProduct.setProduct(productGetId.getId());
                projectProduct.setBranch(0);
                projectProduct.setPlan(0);
                try {
                    int count = projectProductMapper.insert(projectProduct);
                    if (count > 0) {
                        LOG.info("项目与迭代关系创建成功");
                    } else {
                        LOG.info("项目与迭代关系创建失败");
                    }
                }catch (Exception e){
                    return project1.getId();
                }
            return project1.getId();
            }
        }else {
            LOG.info("新建迭代创建失败");
            return 0;
        }
        return 0;
    }

    private void updateProductProjectData(Product products,User manageNames) {

        Integer id = products.getId();
        UserView userView = iUserView.selectByAccount(products.getPo());
        List<Project> projectIds = projectMapper.selectByProductId(id);
        if (null != userView && null != projectIds) {
            for (Project projectId:projectIds) {
                //移除老的项目经理的视图
                UserView userOld = iUserView.selectByAccount(products.getPo());
                UserView userNewView = new UserView();
//                if (null != userOld) {
//                    String productView = userOld.getProducts();
//                    String projectView = userOld.getProjects();
//                    String removeProductId = "," + id;
//                    String removeProjectId = "," + projectId.getId();
//                    String newProductView = productView.replaceAll(removeProductId, "");
//                    String newProjectView = projectView.replaceAll(removeProjectId, "");
//                    userNewView.setAccount(products.getPo());
//                    userNewView.setProducts(newProductView);
//                    userNewView.setProjects(newProjectView);
//                    int counts = iUserView.updateProducts(userNewView);
//                    if (counts > 0) {
//                        LOG.info("修改项目经理视图删除成功");
//                    } else {
//                        LOG.info("修改项目经理视图删除失败");
//                    }
//
//                }
                //添加新的项目经理的视图
                UserView newUserView = iUserView.selectByAccount(manageNames.getAccount());
                String productsView = newUserView.getProducts();
                String projectsView = newUserView.getProjects();
                String newProductsView = productsView + "," + id;
                String newProjectsView = projectsView + "," + projectId.getId();
                userNewView.setAccount(manageNames.getAccount());
                userNewView.setProducts(newProductsView);
                userNewView.setProjects(newProjectsView);

                iUnclaimedProject.updatePoByPid(id.toString(),manageNames.getRealname());
                int count = iUserView.updateProducts(userNewView);
                if (count > 0) {
                    LOG.info("修改新项目经理视图成功");
                } else {
                    LOG.info("修改新项目经理视图失败");
                }
                //修改迭代项目经理和项目负责人
                Project project = new Project();
                project.setPo(manageNames.getAccount());
                project.setPm(manageNames.getAccount());
                project.setRelationproject(products.getId().toString());
                int i = projectMapper.updatePoByProductId(project);
                if (i > 0) {
                    LOG.info("修改迭代项目经理迭代负责人成功");
                } else {
                    LOG.info("修改迭代项目经理迭代负责人失败");
                }
            }
        }
    }

    @Override
    public void createSuperModel(){
        List<Product> products = iProduct.selectcCreateProduct();
        for (Product product : products) {

            if (null!=product.getProductPlatform()&&!product.getProductPlatform().equals("")&&product.getProductPlatform().contains("1")&&product.getSelfBuilt().equals("1")){

                SuperProduct selecByProductCode = superProductMapper.selecByProductcode(product.getId().toString());
                if (null!=selecByProductCode){
                    return ;
                }
                SuperProduct superProduct = new SuperProduct();
                superProduct.setProductcode(product.getId().toString());
                superProduct.setProductname(product.getName());
                superProduct.setCreateddate(product.getCreateddate());
                superProduct.setOnlinetime(product.getProjectCompleteDate()!=null?product.getProjectCompleteDate():null);
                superProduct.setCodebranchtime(product.getProjectCompleteDate()!=null?product.getProjectCompleteDate():null);

                superProduct.setDeleted("0");
                if (product.getPo()!=null){
                    superProduct.setPo(product.getPo());
                }

                int insert = superProductMapper.insert(superProduct);
                if (insert>0){
                    LOG.info("super8模块插入成功");
                }else {
                    LOG.info("super8模块插入失败");
                }

            }
        }

    }


}
